<?php
declare (strict_types=1);

namespace addons\Builder\driver\trait;

use addons\Builder\facade\Builder;
use app\common\tool\Result;
use think\Exception;
use think\exception\ValidateException;
use think\facade\View;
use think\Response;
use think\response\Json;

trait TableMethods
{

    /**
     * 原点 2021年7月27日17:22:29 获取相关数据
     */
    public function getList(): Response
    {
        $tc = Builder::TableCache();
        $param = $this->request->get();
        $tableCache = $tc->getData($param['tableUniqueStr']);
        $extraMapData = $tc->getExtraMapData($param['tableUniqueStr'], $this->request->user->id ?? '');

        $tableCache['extra_map'] = $extraMapData['extra_map'] ?? [];
        if (empty($tableCache)) throw new \Exception('页面加载失败，请尝试刷新页面后重试！');
        $ons = ['hasOne', 'append'];
        foreach ($ons as $v) {
            $tableCache[$v] = !empty($this->$v) ? $this->$v : [];
        }
        //定义排序
        $tableCache['sort'] = !empty($this->sort) ? $tc->getSort($param['tableUniqueStr'], $this->sort) : [];
        //简易钩子函数
        $tableCache['takeOver'] = !empty($this->takeOver) ? $this->takeOver : 0;
        //检测是否查询软删除的数据
        $tableCache['withTrashed'] = !empty($this->withTrashed) ? true : false;
        //检测是否只查询软删除的数据
        $tableCache['onlyTrashed'] = !empty($this->onlyTrashed) ? true : false;

        return Result::fastReturn($this->model::getTableList($tableCache, $param, '*', $this->model));
    }


    /**
     * 原点 2021年7月27日11:05:32 公共添加方法
     */
    public function add($tpl = 'form/add')
    {
        try {
            $tc = Builder::TableCache();
            if ($tpl == 'form/add') {
                $tpl = $tc->getView('add');
            }
            $tableData = $tc->getData();

            return View::fetch($tpl, [
                'demo_time'   => time(),
                'field'       => $tc->getModify(),
                'backUrl'     => request()->param('back', ''),
                'unite'       => $tc->getModify('unite'),
                'hideField'   => $tableData ? $tableData['extra_map'] : [],
                'enterSubmit' => $this->enterSubmit ?? true,
            ]);

        } catch (\Exception $e) {

            return $e->getMessage();
        }
    }

    /**
     * 原点 2021年7月27日11:05:32 公共修改方法
     */
    public function edit($id = '', $tpl = 'form/edit', $info = '')
    {
        try {
            $tc = Builder::TableCache();
            if ($tpl == 'form/edit') {
                $tpl = $tc->getView('edit');
            }
            return View::fetch($tpl, [
                'demo_time'   => time(),
                'field'       => $tc->getModify('edit'),
                'backUrl'     => request()->param('back', ''),
                'unite'       => $tc->getModify('unite'),
                'info'        => $info ?: $this->model::where($this->pk, $id)->find(),
                'enterSubmit' => $this->enterSubmit ?? true,
            ]);
        } catch (\Exception $e) {
            dump($e);die;
            throw new Exception($e->getMessage());
        }
    }

    /**
     * @param array $param -- 新增或修改的数据，支持直接调用和间接调用
     * @param array $model -- 调用model方法，默认false
     *
     * 原点 2021年7月27日14:46:07 公共新增/修改方法
     */
    public function save($param = [], $model = false): Json
    {
        if (!$this->allowVerify()) return json(['code' => -1, 'msg' => '无权限']);

        $param = empty($param) ? $this->request->post() : $param;
        if (!empty($this->validate)) {
            try {
                $this->validate($param, $this->validate);
            } catch (ValidateException $e) {
                return json(['code' => -1, 'msg' => $e->getError()]);
            }
        }
        $action = $model ? '_save' : '_magic';
        return json($this->model::$action($param, $this->getLogsArguments($param, 1)));
    }

    /**
     * 原点 2021年7月27日14:46:29 公共修改字段方法
     */
    public function update(): Json
    {
        try {
            if (!$this->allowVerify()) return json(['code' => -1, 'msg' => '无权限']);
            $param = $this->request->param();
            return json($this->model::_update($param, $this->getLogsArguments($param)));
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 原点 2021年7月27日14:46:29 公共删除方法
     */
    public function delete(): Response
    {
        try {
            if (!$this->allowVerify()) return json(['code' => -1, 'msg' => '无权限']);
            $param = $this->request->param();
            return json($this->model::_delete($param, $this->getLogsArguments($param)));
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }

    public function getLogsArguments($param, $type = ''): array
    {
        $data = [
            'pk'               => $this->pk,
            'tableUniqueTitle' => isset($param['tableUniqueTitle']) ? $param['tableUniqueTitle'] : '',
            'admin'            => $this->admin,
            'writeLog'         => isset($this->writeLog) ? $this->writeLog : 1,
            'writeLogKey'      => isset($this->writeLogKey) ? $this->writeLogKey : ['key' => 'title,code', 'val' => '名称,编号'],
            'withTrashed'      => !empty($this->withTrashed) ? true : false
        ];

        if ($type && isset($param['tableUniqueStr'])) {
            $data['editField'] = Builder::TableCache()->getModify('edit', $param['tableUniqueStr']);
        }
        return $data;
    }


    public static function getStatus(): array
    {
        return [0 => '停用', 1 => '启用'];
    }

    protected function allowVerify()
    {
        if (request()->admin->id != 1) {
            if (!request()->admin->is_lock) return false;
        }
        return true;
    }

}
